121. Best Time to Buy and Sell Stock [easy] (Python)

题目链接

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

题目原文

Say you have an array for which the ith element is the price of a given stock on day i <script type="math/tex" id="MathJax-Element-2">i</script>.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

题目翻译

假设有一个数组,它的第i项是第i天的股票价格。如果你最多只能进行一次买卖操作(买一次,卖一次),设计一个算法求出最大的收益。

思路方法

直观的理解,就是求数组中 max(array[j]-array[i]), j>=i。用两重循环求出每一对不同i,j的差值,这样做会超时,所以要用更巧妙的方法。

思路一

实际上,一次循环就可以求出结果。在遍历的过程中,用一个变量保存目前为止最小的数,用当前的数与目前最小的数相减,判断这个差与此前得到的最大收益的大小,取较大值更新最大收益。

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0:
            return 0
        minPrice = prices[0]
        maxProfit = 0
        for p in prices:
            if p < minPrice:
                minPrice = p
            elif p - minPrice > maxProfit:
                maxProfit = p - minPrice
        return maxProfit

思路二

实际上,这道题本质上是个动态规划问题。如果上面的代码不太好理解,可以尝试理解下面的代码。

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) == 0:
            return 0
        minPrice = prices[0]
        dp = [0] * len(prices)
        for i in xrange(0, len(prices)):
            dp[i] = max(dp[i-1], prices[i] - minPrice)
            minPrice = min(minPrice, prices[i])
        return dp[-1]

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51520971

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值